<?php

namespace App\Http\Controllers\Api;

use App\Services\Wish;
use App\Model\CityModel;
use App\Model\Config;
use App\Model\SkuModel;
use App\Model\WishModel;
use App\Model\UserModel;
use App\Model\UserEnergy;
use App\Model\ConfigModel;
use Illuminate\Http\Request;
use App\Model\UserEnergyLog;
use App\Model\ShopGoodModel;
use App\Model\UserWishOrder;
use App\Model\UserWishLog;
use App\Model\UserLoginModel;
use App\Model\UserWalletModel;
use App\Model\UserAddressModel;
use App\Model\UserWalletLogModel;
use App\Model\GroupListOrder;
use App\Model\GroupListLog;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

//心愿单
class WishController extends Controller
{
	//判断用户是否实名认证
	public function is_auth(){
		$uid = request()->uid;
		$user = UserModel::where('id',$uid)->first();
		if($user){
			if($user['is_auth'] != 1){
				return ['code'=>0,'msg'=>"您当前尚未实名认证"];
			}
		}else{
			return ['code'=>0,'msg'=>"用户不存在"];
		}
		return ['code'=>1,'msg'=>"ok"];
	}


	//用户的心愿首页
	public function is_exit(){
		//用户ID
		$uid = request()->uid;
		//用户信息
		$user = UserModel::where('id',$uid)->first();
		//用户的能量
		$user_energy = UserEnergy::where('uid',$uid)->first();
		//用户的心愿
		$user_wish = WishModel::where('uid',$uid)->where('state',1)->first();
		$data['gname'] = '暂无';
		$data['gid'] = 0;
		$data['gpicname'] = "http://".$_SERVER['HTTP_HOST'].'/img/good.png';
		$data['total'] = 0;
		$data['in_total'] = 0;
		$data['red'] = 0;
		$data['blue'] = 0;
		$data['state_cy'] = 0;
		$data['wid'] = 0;
		//用户是否存有汽油
		if($user_energy){
			$data['red'] = $user_energy['sys_num']+$user_energy['oth_num'];
			$data['blue'] = $user_energy['sys_num_two']+$user_energy['oth_num_two'];
		}
		//用户是否有心愿单
		if($user_wish){
			if($user_wish['in_total'] >= $user_wish['total']){
				$data['state_cy'] = 1;
			}
			$data['gname'] = $user_wish['gname'];
			$data['gid'] = $user_wish['gid'];
			$data['gpicname'] = "http://".$_SERVER['HTTP_HOST'].$user_wish['picname'];
			$has = '/upload/shop';
			if(strpos($data['gpicname'],$has) !== FALSE){
				$data['gpicname'] = 'http://'.$_SERVER['HTTP_HOST'].$user_wish['picname'];
			}else{
				$data['gpicname'] = $user_wish['picname'];
			}
			
			$data['total'] = $user_wish['total'];
			$data['in_total'] = $user_wish['in_total'];
			$data['wid'] = $user_wish['id'];
		}
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//加入心愿单
	public function add_wish(){
		$uid = request()->uid;
		//用户信息
		$user = UserModel::where('id',$uid)->first();
		//商品信息
		$good = ShopGoodModel::where('id',request()->gid)->first();
		//用户的心愿单
		$user_wish = WishModel::where('uid',$uid)->where('state',1)->first();
		//用户是否存在相同商品已完成的心愿单
		$user_wish_exit = WishModel::where('uid',$uid)->where('gid',request()->gid)->where('sku_id',request()->sku_id)->where('state',2)->first();
		if($user['is_auth'] != 1){
			return ['code'=>0,'msg'=>'当前尚未实名认证，不可加入心愿单'];
		}
		if(!empty($user_wish)){
			return ['code'=>'0','msg'=>'当前存在正在进行的心愿单，不可进行此操作'];
		}
		if($good['is_wish'] != 1){
			return ['code'=>0,'msg'=>'当前商品不可加入心愿单'];
		}
		if($user_wish_exit){
			return ['code'=>0,'msg'=>'心愿单已存在该商品，不可重复加入'];
		}
		if($good['is_attr'] == 1){
			if(request()->sku_id <= 0){
				return ['code'=>"0",'msg'=>"请选择规格"];
			}
		}
		$cost = $good['cost_price'];
		$sell = $good['sell_price'];
		$good['picname'] = $good['picpath'].$good['picname'];
		if($good['oss_pic']){
			$good['picname'] = $good['oss_pic'];
		}
		//判断库存
		//选择有规格的商品
		if(request()->sku_id > 0){
			$sku_list = SkuModel::where('gid',request()->gid)->where('id',request()->sku_id)->first();
			$num = $sku_list['sum'];
			$cost = $sku_list['cost_price'];
			$sell = $sku_list['sell_price'];
			if($sku_list['oss_pic']){
				$good['picname'] = $sku_list['oss_pic'];
			}else{
				$good['picname'] = $sku_list['picname'];
			}
		}else{
			$num = $good['num'];
		}
		if($num <= 0){
			return ['code'=>0,'msg'=>'库存不足'];
		}
		//百分比
		$wish_end_ratio = ConfigModel::getValue('wish_end_ratio');
		$wish_days = ceil($sell*$wish_end_ratio);
		$wish_end_time = date('Y-m-d',strtotime('+'.$wish_days.' days'));
		//里程数倍数
		$km_times = ConfigModel::getValue('km_times');
		//加入心愿单
		DB::beginTransaction();
		try{
			WishModel::create([
				'uid' => $uid,
				'gid' => request()->gid,
				'sku_id' => request()->sku_id,
				'gname' => $good['name'],
				'cost_price' => $cost,
				'sell_price' => $sell,
				'picname' => $good['picname'],
				'total' => $sell*$km_times,
				'days' => $wish_days,
				'wish_end_time' => $wish_end_time,
				'sku_attr' => request()->sku_attr,
			]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>"心愿单加入成功"];
		
	}

	//我的好友
	public function friends(){
		$uid = request()->uid;
		$user = UserModel::where('id',$uid)->first();
		//上级
		$pid = $user['pid'].',';
		//直推下级
		$user_push = UserModel::where('pid',$user['id'])->get();
		foreach($user_push as $k=>$v){
			$pid .= $v['id'].',';
		}
		$pid = explode(',',trim($pid,','));

		$friends = [];
		foreach($pid as $k=>$v){
			$puser = UserModel::where('id',$v)->first();
			if($puser['is_auth'] != 1){
				continue;
			}
			$friends[$k]['id'] = $puser['id'];
			$friends[$k]['user'] = $puser['user'];
			//用户是否第三方
			$party = UserLoginModel::where('uid',$puser['id'])->first();
			if(empty($puser->picname)){
				if(empty($party['picname'])){
					$friends[$k]['picname'] = "http://".$_SERVER['HTTP_HOST']."/user.png";
				}else{
					$friends[$k]['picname'] = $party['picname'];
				}
			}else{
				$friends[$k]['picname'] = "http://".$_SERVER['HTTP_HOST'].$puser->picname;
			}
			//用户的能量
			$user_energy = UserEnergy::where('uid',$puser['id'])->first();
			$friends[$k]['blue'] = $user_energy['sys_num_two'] + $user_energy['oth_num_two'];
			//用户的心愿单
			$user_wish = WishModel::where('uid',$puser['id'])->where('state',1)->first();
			$friends[$k]['gname'] = '暂无心愿';
			$friends[$k]['total'] = 0;
			$friends[$k]['in_total'] = 0;
			if($user_wish){
				$friends[$k]['gname'] = $user_wish['gname'];
				$friends[$k]['total'] = $user_wish['total'];
				$friends[$k]['in_total'] = $user_wish['in_total'];
			}
		}
		return ['code'=>1,'msg'=>"返回数据",'data'=>array_values($friends)];
	}

	//判断今日是否签到
	public function is_energy(){
		$h = date('H');
		if($h >= 5){
			$start = date('Y-m-d 05:00:00');
			$end = date('Y-m-d 05:00:00',strtotime('+1 day'));

		}else{
			$start = date('Y-m-d 05:00:00',strtotime('-1 day'));
			$end = date('Y-m-d 05:00:00');
		}
		//红桶
		$red_exit = UserEnergyLog::whereBetween('created_at',[$start,$end])->where('uid',request()->uid)->where('type',1)->where('status',1)->first();
		//蓝桶
		$blue_exit = UserEnergyLog::whereBetween('created_at',[$start,$end])->where('uid',request()->uid)->where('type',1)->where('status',3)->first();
		$red = 0;
		$blue = 0;
		if($red_exit){
			$red = 1;
		}
		if($blue_exit){
			$blue = 1;
		}
		$data['red'] = $red;
		$data['blue'] = $blue;
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//领取汽油
	public function add_energy(Request $request){
		//用户ID
		$uid = $request->input('uid');
		//签到类型
		$type = $request->input('type',1);
		//用户心愿
		$user_wish = WishModel::where('uid',$uid)->where('state',1)->first();
		if(!$user_wish){
			return ['code'=>0,'msg'=>'当前暂无心愿,不可进行此操作'];
		}
		$h = date('H');
		if($h >= 5){
			$start = date('Y-m-d 05:00:00');
			$end = date('Y-m-d 05:00:00',strtotime('+1 day'));

		}else{
			$start = date('Y-m-d 05:00:00',strtotime('-1 day'));
			$end = date('Y-m-d 05:00:00');
		}
		$num = 0;
		$red_num = ConfigModel::getValue('red_num');
		$blue_num = ConfigModel::getValue('blue_num');
		//用户能量
		$user_energy = UserEnergy::where('uid',$uid)->first();
		//红桶
		$red_exit = UserEnergyLog::whereBetween('created_at',[$start,$end])->where('uid',request()->uid)->where('type',1)->where('status',1)->first();
		//蓝桶
		$blue_exit = UserEnergyLog::whereBetween('created_at',[$start,$end])->where('uid',request()->uid)->where('type',1)->where('status',3)->first();
		DB::beginTransaction();
		try{
			switch($type){
				//红桶
				case '1':
					if($red_exit){
						return ['code'=>0,'msg'=>'您当日已签到,不可重复此操作'];
					}
					//增加数量
					if($user_energy){
						$user_energy->increment('sys_num',$red_num);
					}else{
						UserEnergy::create([
							'uid' => $uid,
							'sys_num' => $red_num,
						]);
					}
					//增加日志
					UserEnergyLog::add_log($uid,$red_num,'+','1','1','每日签到获得'.$red_num.'桶红汽油','0');
					$num = $red_num;
					break;
				//蓝桶
				case '2':
					if($blue_exit){
						return ['code'=>0,'msg'=>'您当日已签到,不可重复此操作'];
					}

					//增加数量
					if($user_energy){
						$user_energy->increment('sys_num_two',$blue_num);
					}else{
						UserEnergy::create([
							'uid' => $uid,
							'sys_num_two' => $blue_num,
						]);
					}
					$num = $blue_num;
					//增加日志
					UserEnergyLog::add_log($uid,$blue_num,'+','1','3','每日签到获得'.$blue_num.'桶蓝汽油','0');
					break;
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'签到失败'];
		}
		return ['code'=>1,'msg'=>'签到成功','data'=>$num];
	}

	//心愿记录
	public function wish_log(){
		$uid = request()->uid;
		$wish_log = WishModel::where('uid',$uid)->select('id','gname','created_at','state','over_time','no_time','updated_at')->orderby('updated_at','desc')->get();
		$user_wish = [];
		foreach($wish_log as $k=>$v){
			$user_wish[$k]['id'] = $v['id'];
			$user_wish[$k]['gname'] = $v['gname'];
			$user_wish[$k]['state'] = $v['state'];
			$user_wish[$k]['order_state'] = 2;
			$user_wish[$k]['wish_oid'] = 0;
			if(UserWishOrder::where('wid',$v['id'])->value('id') > 0){
				$user_wish[$k]['wish_oid'] = UserWishOrder::where('wid',$v['id'])->value('id');
			}

			if($v['state'] == 1){
				$user_wish[$k]['state_name'] = '进行中';
				$user_wish[$k]['time'] = date('Y-m-d H:i:s',$v->created_at->timestamp);
			}elseif($v['state'] == 2){
				$wish_order = UserWishOrder::where('wid',$v['id'])->first();
				if($wish_order['state'] == 1){
					$user_wish[$k]['state_name'] = '已完成,待发货';
				}elseif($wish_order['state'] == 2){
					$user_wish[$k]['order_state'] = 1;
					$user_wish[$k]['state_name'] = '已完成,待收货';
				}elseif($wish_order['state'] == 3){
					$user_wish[$k]['order_state'] = 1;
					$user_wish[$k]['state_name'] = '已领取';
				}
				$user_wish[$k]['time'] = $v['over_time'];
			}elseif($v['state'] == 3){
				$user_wish[$k]['state_name'] = '已撤销';
				$user_wish[$k]['time'] = $v['no_time'];
			}elseif($v['state'] == 4){
				$user_wish[$k]['state_name'] = '已失效';
				$user_wish[$k]['time'] = date('Y-m-d H:i:s',$v->updated_at->timestamp);
			}
		}

		return ['code'=>1,'msg'=>'返回数据','data'=>$user_wish];
	}

	//动态日志
	public function energy_log(){
		$uid = request()->uid;
		$log = DB::table('user_energy_log')->select('date')->distinct(true)->where('uid',$uid)->orderBy('date','desc')->get();

		foreach($log as $k=>$v){
			$arr = [];
			$list = UserEnergyLog::where('date',$v->date)->where('uid',$uid)->orderBy('created_at','desc')->get();
			foreach($list as $key=>$val){
				$user = UserModel::where('id',$val['uid'])->first();
				$arr[$key]['id'] = $val['id'];
				$arr[$key]['remark'] = $val['remark'];
				if($val['status'] == 2){
					$arr[$key]['type_cy'] = 1;
				}else{
					$arr[$key]['type_cy'] = 2;
				}
				$arr[$key]['time'] = substr(date('Y-m-d H:i:s',$val->created_at->timestamp),11,8);
				//用户是否第三方
				$party = UserLoginModel::where('uid',$val['uid'])->first();
				if(empty($user->picname)){
					if(empty($party['picname'])){
						$arr[$key]['picname'] = "http://".$_SERVER['HTTP_HOST']."/user.png";
					}else{
						$arr[$key]['picname'] = $party['picname'];
					}
				}else{
					$arr[$key]['picname'] = "http://".$_SERVER['HTTP_HOST'].$user->picname;
				}

			}
			$log[$k]->list = $arr;
		}
		return ['code'=>1,'msg'=>'返回数据','data'=>$log];

	}

	//浇汽油(自己)
	public function del_energy(Request $request){
		//用户ID
		$uid = request()->uid;
		//心愿ID
		$wish = WishModel::where('uid',$uid)->where('state',1)->first();
		if(!$wish){
			return ['code'=>'0','msg'=>'您当前暂无心愿,不可进行此操作'];
		}
		//类型
		$type = $request->input('type',1);
		//用户的能量
		$user_energy = UserEnergy::where('uid',$uid)->first();

		DB::beginTransaction();
		try{
			switch($type){
				case '1':
					//判断油桶是否充足
					if($user_energy['sys_num']+$user_energy['oth_num'] <= 0){
						return ['code'=>0,'msg'=>'当前红油桶不足，完成任务得油桶'];
					}
					if($wish['in_total'] >= $wish['total']){
						return ['code'=>0,'msg'=>'您的心愿已完成,快去领取吧!'];
					}
					//用户当前红油 总桶数量
					$all_red_nums =  $user_energy['sys_num'] + $user_energy['oth_num'];
					//剩余里程数
					$due_nums = $wish['total'] - $wish['in_total'];
					//预留百分比
					$due_km_ratio = ConfigModel::getValue('due_km_ratio');
					
					$oiling = new Wish;
					$return_nums = $oiling->oiling($all_red_nums,$due_nums*$due_km_ratio,1,0,$wish['id'],$wish['sell_price'],$uid);
					$total_num = $return_nums['one']+$return_nums['two'];
					UserEnergyLog::add_log($uid,$total_num,'-','4','5','成功加了'.$total_num.'桶红汽油',$uid,$wish['id'],$return_nums['one'],$return_nums['two']);

					break;
				case '2':
					return ['code'=>0,'msg'=>'蓝桶汽油仅可浇灌好友的心愿'];
					break;
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'操作成功'];
	}
	//好友心愿首页
	public function friends_home(){
		//好友ID
		$tid = request()->tid;
		//用户ID
		$uid = request()->uid;
		//用户的心愿
		$user_wish = WishModel::where('uid',$tid)->where('state',1)->first();
		$data = [];
		if($user_wish){
			$data['gname'] = $user_wish['gname'];
			$data['gid'] = $user_wish['gid'];
			$data['picname'] = 'http://'.$_SERVER['HTTP_HOST'].$user_wish['picname'];

			$has = '/upload/shop';
			if(strpos($data['picname'],$has) !== FALSE){
				$data['picname'] = 'http://'.$_SERVER['HTTP_HOST'].$user_wish['picname'];
			}else{
				$data['picname'] = $user_wish['picname'];
			}
			$data['in_total'] = $user_wish['in_total'];
			$data['total'] = $user_wish['total'];
		}else{
			$data['gname'] = '暂无';
			$data['gid'] = 0;
			$data['picname'] = 'http://'.$_SERVER['HTTP_HOST']."/img/good.png";
			$data['in_total'] = 0;
			$data['total'] = 0;
		}
		//本人的蓝色油桶
		$user_energy = UserEnergy::where('uid',$uid)->first();
		if($user_energy){
			$blue = $user_energy['sys_num_two']+$user_energy['oth_num_two'];
		}else{
			$blue = 0;
		}
		$res['data'] = $data;
		$res['blue'] = $blue;
		return ['code'=>1,'msg'=>"返回数据",'data'=>$res];
	}

	//给好友交汽油
	public function friends_energy(){
		$uid = request()->uid;
		$tid = request()->tid;
		$num = request()->num;
		$num_str = "/^[1-9]\d*$/";

		if($num <= 0){
			return ['code'=>0,'msg'=>'请输入数字'];
		}
		if (!preg_match($num_str, $num)) {
			return ['code' => 0, 'msg' => '请输入整数'];
		}
		if($uid == $tid){
			return ['code'=>0,'msg'=>'自己不可以使用蓝桶汽油'];
		}
		//好友昵称
		$tuser = UserModel::where('id',$tid)->value('user');
		//本人昵称
		$user = UserModel::where('id',$uid)->value('user');
		//好友当前是否存在心愿
		$tuser_wish = WishModel::where('uid',$tid)->where('state',1)->first();
		if(!$tuser_wish){
			return ['code'=>0,'msg'=>'好友当前暂无心愿,不可进行此操作'];
		}
		//用户的汽油信息
		$user_energy = UserEnergy::where('uid',$uid)->first();
		if(!$user_energy){
			return ['code'=>0,'msg'=>'当前油桶不足'];
		}
		if($user_energy['sys_num_two'] + $user_energy['oth_num_two'] < $num){
			return ['code'=>0,'msg'=>'当前油桶不足'];
		}
		DB::beginTransaction();
		try{
			//系统蓝桶的数量
			$sys_num = $user_energy['sys_num_two'];
			//剩余扣除的蓝桶
			$oth_num = $num-$sys_num;
			if($user_energy['oth_num_two'] < $oth_num){
				return ['code'=>0,'msg'=>'当前油桶不足'];
			}

			//预留百分比
			$due_km_ratio = ConfigModel::getValue('due_km_ratio');

			//当前还有剩余里程数
			$due = $tuser_wish['total'] - $tuser_wish['in_total'];
			$oiling = new Wish();
			
			$return_nums = $oiling->oiling($num,$due*$due_km_ratio,2,0,$tuser_wish['id'],$tuser_wish['sell_price'],$uid,$one=0,$two=0,$tid);
			$total_num = $return_nums['one']+$return_nums['two'];
			//增加日志
			//-
			UserEnergyLog::add_log($uid,$total_num,'-','5','6','你帮<span style="color:#FF8E31">'.$tuser.'</span>加了'.$total_num.'桶蓝汽油',$tid,$tuser_wish['id'],0,0,$return_nums['one'],$return_nums['two']);
			//+
			UserEnergyLog::add_log($tid,$total_num,'+','2','6','<span style="color:#289DFF">'.$user.'</span>帮你加了'.$total_num.'桶蓝汽油',$uid,$tuser_wish['id'],0,0,$return_nums['one'],$return_nums['two']);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'操作失败'];
		}
		return ['code'=>'1','msg'=>'操作成功'];

	}

	//领取
	public function get_wish(){
		$uid = request()->uid;
		$wid = request()->wid;

		//用户地址
		$add_cy = [];
		$address = UserAddressModel::where('uid',$uid)->where('is_default',1)->first();
		if(!$address){
			$address = UserAddressModel::where('uid',$uid)->orderBy('id','desc')->first();
			if($address){
				$add_cy['id'] = $address['id'];
				$add_cy['name'] = $address['name'];
				$add_cy['phone'] = $address['phone'];
				$add_cy['address'] = UserAddressModel::city($address['provinceid']).UserAddressModel::city($address['cityid']).UserAddressModel::city($address['cityid']).$address['detail'];
			}
		}else{
			$add_cy['id'] = $address['id'];
			$add_cy['name'] = $address['name'];
			$add_cy['phone'] = $address['phone'];
			$add_cy['address'] = UserAddressModel::city($address['provinceid']).UserAddressModel::city($address['cityid']).UserAddressModel::city($address['cityid']).$address['detail'];
		}
		//是否存在地址
		$is_add = 1;
		if(!$address){
			$is_add = 2;
		}

		//商品信息
		$user_wish = WishModel::where('id',$wid)->where('state',1)->first();//->where('uid',$uid)
		if(!$user_wish){
			return ['code'=>0,'msg'=>'该心愿当前不可领取'];
		}
		if($user_wish['in_total'] < $user_wish['total']){
			return ['code'=>0,'msg'=>'该心愿当前不可领取'];
		}
		$good['name'] = $user_wish['gname'];
		$good['picname'] = 'http://'.$_SERVER['HTTP_HOST'].$user_wish['picname'];
		$has = '/upload/shop';
		if(strpos($good['picname'],$has) !== FALSE){
			$good['picname'] = 'http://'.$_SERVER['HTTP_HOST'].$user_wish['picname'];
		}else{
			$good['picname'] = $user_wish['picname'];
		}

		$good['sku_attr'] = $user_wish['sku_attr'];
		$good['sku_id'] = $user_wish['sku_id'];
		$good['sell_price'] = $user_wish['sell_price'];
		if($good['sku_id'] == 0){
			$good['sku_attr'] = '无规格';
		}
		$data['address'] = $add_cy;
		$data['is_add'] = $is_add;
		$data['good'] = $good;
		$data['wid'] = $user_wish['id'];
		$data['ticket_num'] = $user_wish['in_total'];
		$data['due_num'] = $user_wish['total'] - $user_wish['in_total'];

		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//确认 商品,商城订单
	public function create_wish(Request $request){
		//心愿ID
		$wid = request()->wid;
		//地址ID
		$linkname = request()->linkname;
		$linktel = request()->linktel;
		$detail = request()->detail;
		if(empty($linkname) || empty($linktel) || empty($detail)){
			return ['code'=>0,'msg'=>"请选择收货人信息"];
		}
		//用户ID
		$uid = request()->uid;
		//用户信息
		$user = UserModel::where('id',$uid)->first();
		if(!$user){
			return ['code'=>0,'msg'=>'该用户信息有误'];
		}
		//心愿
		$wish = WishModel::where('id',$wid)->where('state',1)->first();
		if(!$wish){
			return ['code'=>0,'msg'=>"该心愿当前不可领取"];
		}
		//需要支付多少钱
		$due_num = $wish['total'] - $wish['in_total'];
		//支付类型
		$type = request()->paytype;
		//用户的资产信息
		$user_wallet = UserWalletModel::where('uid',$uid)->first();
		DB::beginTransaction();
		try{
			if($type){
				if($due_num <= 0){
					return ['code'=>'0','msg'=>'当前心愿单可直接兑换'];
				}
				//是否输入二级密码
				if(!request()->paypass){
					return ['code'=>0,'msg'=>retStrInfo(10)];
				}
				//二级密码是否正确
				if (!Hash::check(request()->paypass, $user['paypass'])) {
					return ['code' => 0, 'msg' => retStrInfo(56)];
				}
				switch($type){
					//现金购买
					case '1':
						if($user_wallet['money'] < $due_num){
							return ['code'=>0,'msg'=>'当前可用资产不足'];
						}
						//资产日志
						UserWalletModel::handleAccount($uid,$due_num,'-','结算心愿单，商品名：【'.$wish['gname'].'】','1','16','user_wish',$wid);
						break;
					//货款购买
					case '2':
						if($user_wallet['lock_money'] < $due_num){
							return ['code'=>0,'msg'=>'当前可用资产不足'];
						}
						//资产日志
						UserWalletModel::handleAccount($uid,$due_num,'-','结算心愿单，商品名：【'.$wish['gname'].'】','1','16','user_wish',$wid);
						break;

				}
				//心愿单日志
				UserEnergyLog::create(
					[
						'wid' => $wid,
						'uid' => $uid,
						'num' => $due_num,
						'sign' => '-',
						'type' => 6,
						'status' => 7,
						'remark' => '结算心愿单，商品名【'.$wish['gname'].'】',
						'date' => date('m-d'),
					]
				);
			}else{
				if($due_num > 0){
					return ['code'=>'0','msg'=>'当前心愿单不可直接兑换'];
				}
			}
			if(!$type){
				$type = 3;
			}
			//更改心愿的状态,完成时间
			WishModel::where('id',$wid)->update(['over_time'=>date('Y-m-d H:i:s'),'state'=>2]);
			//生成订单
			UserWishOrder::create([
				'uid' => $uid,
				'wid' => $wid,
				'linkname' => $linkname,
				'linktel' => $linktel,
				'address' => $detail,
				'on_sn' => UserWishOrder::make_no(),
				'paytype' => $type,
				]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'下单失败'];
		}
		return ['code'=>1,'msg'=>'下单成功'];
	}

	//物流
	public function logistics(Request $request){
		//订单ID
		$id = request()->id;
		$type = $request->input('type',1);

		if($type == 2){
			$list = GroupListLog::where('oid',$id)->where('state',3)->first();
			if(!$list){
				return ['code'=>0,'msg'=>'该订单不存在'];
			}
			$state = $list['status'];
		}else{
			$list = UserWishOrder::where('id',$id)->first();
			if(!$list){
				return ['code'=>0,'msg'=>'该订单不存在'];
			}
			$state = $list['state'];
		}
			

			
		// 	//收货省份
		// 	$address = GroupListOrder::where('id',$list['oid'])->value('address');
		// 	$express_num = $list['express_num'];
		// 	$express_com = $list['express_com'];
		// 	break;
		// }
		
		if(!$list){
			return ['code'=>0,'msg'=>'该订单有误'];
		}
		$address = $list['address'];
		$express_num = $list['express_num'];
		$express_com = $list['express_com'];
		
		$data = [];
		
		//物流信息
		$a = [];
		if(!empty($list['express_num'])){
			$a = $this->get($list['express_num']);
		}
		
		$arr = explode('省',$address);
		if(count($arr)<2){
			$arr = explode('区',$address);

			if(count($arr) < 2){
				$arr = explode('市',$address);
				if(!count($arr) < 2){
					$arr_cy = $address;
				}else{
					$arr_cy = $arr[0].'市';
				}
				
			}else{
				$arr_cy = $arr[0].'区';
			}
			
		}else{
			$arr_cy = $arr[0].'省';
		}
		// dd(1);
		$data['id'] = $id;
	
		$data['express_num'] = $express_num;
		$data['express_com'] = $express_com;
		$data['state'] = $state;
		$data['city'] = $arr_cy;
		if($a){
			$data['express'] = $a['data'];
		}else{
			$data['express'] = [];
		}

		
		
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	// 查询快递信息
	public function get($num){
		$url = "http://www.kuaidi100.com/autonumber/auto?num={$num}&key=jyFUDdqL8938";
		$str = file_get_contents($url);
		$arr = json_decode($str,true);
	
		foreach ($arr as $key => $value) {
			$res = $this->express($value['comCode'], $num);
		
			if($res['message'] == "ok"){
				return $res;
			}
		}
	}

	/**
	物流  快递100
	name   物流公司名称 （shunfeng 顺丰） 可在官网查看物流公司的简称
	number   单号
	 */
	public function express($name,$number){
		//参数设置
		$post_data = array();
		$post_data["customer"] = '8AA707C0A4AFB0A29CC76525E2679114';
		$key= 'jyFUDdqL8938' ;

		$data['com']=$name;  //查询的快递公司的编码， 一律用小写字母
		$data['num']=$number;  //查询的快递单号， 单号的最大长度是32个字符 358263398950
		$post_data["param"] =json_encode($data);

		$url='http://poll.kuaidi100.com/poll/query.do';
		$post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
		$post_data["sign"] = strtoupper($post_data["sign"]);
		$o="";
		foreach ($post_data as $k=>$v)
		{
			$o.= "$k=".urlencode($v)."&";       //默认UTF-8编码格式
		}
		$post_data = substr($o,0,-1);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
		curl_setopt($ch, CURLOPT_TIMEOUT,3);
		$result = curl_exec($ch);
		curl_close($ch);
		$data = json_decode($result,true);
		return $data;
	}

	//撤销订单
	public function cancle(){
		//订单ID
		$id = request()->id;
		//心愿信息
		$wish = WishModel::where('id',$id)->first();
		if(!$wish){
			return ['code'=>0,'msg'=>'该心愿不存在'];
		}
		if($wish['state'] != 1){
			return ['code'=>0,'msg'=>"该心愿当前不可撤销"];
		}
		DB::beginTransaction();
		try{
			//更改心愿单状态：已撤销
			WishModel::where('id',$id)->update(['state'=>3,'no_time'=>date('Y-m-d H:i:s')]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'撤销失败'];
		}
		return ['code'=>1,'msg'=>'已撤销'];
	}
}